package BtoB.util;



import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParser {	
	Map<String,ItemValueObject> items; 
	
	public DOMParser(Map<String,ItemValueObject> items) {
		this.items = items;
	}
		
	public Map<String, ItemValueObject> parseXMLFiles(List<String> fileList){
		if(fileList.size() > 0){
			for(String filename:fileList){
				this.parseXmlFile(filename);
			}
		}
		else{
			System.out.println("XML file list is empty!");
		}
		
		return new HashMap<String,ItemValueObject>(items);
	}
	
	private void parseXmlFile(String filename){
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document dom = db.parse(filename);
			this.parseDocument(dom);
		}
		catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	private void parseDocument(Document dom){
		Element docEle = dom.getDocumentElement();
		NodeList nl = docEle.getElementsByTagName("item");
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {
				Element el = (Element)nl.item(i);
				String itemNumber = el.getAttribute("number");
				String itemName = getTextValue(el,"name");
				Integer itemQty = getIntValue(el,"quantity");
				ItemValueObject itemVO = new ItemValueObject();
				itemVO.setItemNumber(itemNumber);
				itemVO.setItemName(itemName);
				itemVO.setOrderQty(itemQty);
				this.addItems(itemVO);
			}
		}
	}
	
	private void addItems(ItemValueObject item){
		//if containing this item number
		if ( items.containsKey(item.getItemNumber()))	{
			int qty = items.get(item.getItemNumber()).getOrderQty();
			ItemValueObject newItemVO = new ItemValueObject();
			newItemVO.setItemName(item.getItemName());
			newItemVO.setItemNumber(item.getItemNumber());
			newItemVO.setOrderQty(qty+item.getOrderQty());			
			items.put(item.getItemNumber(),newItemVO);
		}
		else{
			items.put(item.getItemNumber(), item);		
		}		
	}
	
	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}
		return textVal;
	}

	private int getIntValue(Element ele, String tagName) {
		//in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele,tagName));
	}
}
